﻿using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Xunit;

namespace MyDemo
{
    /// <summary>
    /// http://www.cnblogs.com/zhaopei/p/5769782.html#top
    /// </summary>
    public class Class5
    {
        [Fact]
        public void Test()
        {
            MyCollection my = new MyCollection(new[] { "1", "2" });

            List<string> result = new List<string>();

            foreach (var item in my)
            {
                Debug.WriteLine(item.ToString());
            }
        }
    }

    /// <summary>
    /// 如果不实现IEnumerable接口, 只要含有GetEnumerator()方法,功能依然有效
    /// </summary>
    public class MyCollection : IEnumerable
    {
        private string[] strList;

        public MyCollection(string[] list)
        {
            strList = list;
        }

        public IEnumerator GetEnumerator()
        {
            for (int i = 0; i < strList.Length; i++)
            {
                yield return strList[i];
            }
            //return new MyEnumerator(strList);
        }
    }

    /// <summary>
    /// 自定义迭代器
    /// </summary>
    public class MyEnumerator : IEnumerator
    {
        private string[] strList;
        private int index;

        public MyEnumerator(string[] list)
        {
            strList = list;
            index = -1;
        }

        public object Current
        {
            get
            {
                return strList[index];
            }
        }

        public bool MoveNext()
        {
            index++;
            if (index < strList.Length)
            {
                return true;
            }
            return false;
        }

        public void Reset()
        {
            index = -1;
        }
    }
}